/*
    ajax请求函数模块
    返回值: promise对象(异步返回的数据是: response.data)
 */
import axios from 'axios'
import { Config, Catch } from './index';
import { Toast } from "vant"

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

export const unajax = (url, data={}, type='GET')=>{

    return new Promise(function (resolve, reject) {
    // 执行异步ajax请求
        let promise
        if (type === 'GET') {
            // 准备url query参数数据
            let dataStr = '' //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&'
            })
            if (dataStr !== '') {
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
                url = url + '?' + dataStr
            }
            // 发送get请求
            promise = axios.get(url)
        } else {
            // 发送post请求
            promise = axios.post(url, data)
        }
        promise.then(function (response) {
            // 成功了调用resolve()
            resolve(response.data)
        }).catch(function (error) {
            //失败了调用reject()
            if(error.message==="Network Error"){
                Toast.fail('网络错误,请稍后重试')
                return
            }
            reject(error)
        })
    })
}

export const auth_ajax =(url, data={}, type='GET',header={
    headers:{
        'Authorization': Catch.get('access_token')
    }
})=>{
    return new Promise(function (resolve, reject) {
    // 执行异步ajax请求
        let promise
        if (type.toUpperCase() === 'GET') {
            // 准备url query参数数据
            let dataStr = '' //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&'
            })
            if (dataStr !== '') {
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
                url = url + '?' + dataStr
            }
            // 发送get请求
            promise = axios.get(url,header)
        } else {
            // 发送post请求
            promise = axios.post(url, data,header)
        }
        promise.then(function (response) {
            // 成功了调用resolve()
            if(response.data.errcode === 5){
                let ref = auth_ajax(Config.BaseUrl+"refresh",{},'GET',{
                    headers:{
                        'Authorization': Catch.get('refresh_token')
                    }
                });
                ref.then(function (ref_res) {
                    if(ref_res.errcode===0){
                        Catch.set('access_token',ref_res['data']['access_token']);
                        Catch.set('refresh_token',ref_res['data']['refresh_token']);
                        auth_ajax(url,data,type,{
                            headers:{
                                'Authorization': Catch.get('access_token')
                            }
                        }).then(r=>{
                            resolve(r.data)
                        }).catch(e=>{
                            reject(e)
                        })
                    }else{
                        
                        Catch.remove('access_token');
                        Catch.remove('refresh_token');
                        setTimeout(()=>{
                            window.location.reload()
                        },1000);
                    }
                }).catch(function (ref_err) {
                    //失败了调用reject()
                    reject(ref_err)
                })
                //ajax(url,data,type)
            }else{
                resolve(response.data)
            }
        }).catch(function (error) {
            //失败了调用reject()
            reject(error)
        })
    })
}

export const dotnet_ajax =(url, data={}, type='GET',header={
    headers:{
        'Authorization': "Bearer "+Catch.get('access_token')
    }
})=>{
    return new Promise(function (resolve, reject) {
    // 执行异步ajax请求
        let promise
        if (type.toUpperCase() === 'GET') {
            // 准备url query参数数据
            let dataStr = '' //数据拼接字符串
            Object.keys(data).forEach(key => {
                dataStr += key + '=' + data[key] + '&'
            })
            if (dataStr !== '') {
                dataStr = dataStr.substring(0, dataStr.lastIndexOf('&'))
                url = url + '?' + dataStr
            }
            // 发送get请求
            promise = axios.get(url, header)
        } else {
            // 发送post请求
            promise = axios.post(url, data, header)
        }
        promise.then(function (response) {
            // 成功了调用resolve()
            resolve(response.data)
        }).catch(function (error) {
            //失败了调用reject()
            let d = error.response;
            if(error.message==="Network Error"){
                Toast.fail('网络错误,请稍后重试')
                return
            }
            if(d.status===401){
                Catch.remove('access_token');
                window.location.reload()
            }else{
                reject(error)
            }
        })
    })
}

export const down_blob = (baseURL,url, onprogress)=>{
    return new Promise(function (resolve, reject) {
        axios.create({
            baseURL,
            method:'get',
            responseType:'blob',
            timeout: 180 * 1000,
            onDownloadProgress: progressEvent=>{
                if(onprogress) onprogress(progressEvent)
            }
        }).get(url).then(res=>{
            resolve(res.data)
        }).catch(function (error) {
            //失败了调用reject()
            if(error.message==="Network Error"){
                Toast.fail('网络错误,请稍后重试')
                return
            }
            reject(error)
        })
    })
}

export default dotnet_ajax;